<template>
  <div id="reportManager">
    <Breadcrumb :content="content"></Breadcrumb>
    <div class="bodyContent">
      <el-tabs type="border-card">
        <el-tab-pane label="报告模版">
          <ReportInfoInstrumentRpt />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script setup lang="ts">
// 公共组件标题
const content = ref('报表设置');
import { ref, reactive, getCurrentInstance, watch } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { pageSizes, notifyType, notifyMessage } from '@/utils/common';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { VxeTablePropTypes } from 'vxe-table';
import { ElMessage } from 'element-plus';
import 'splitpanes/dist/splitpanes.css';
import { VXETable } from 'vxe-table';
import XEUtils from 'xe-utils';
import { VxeMessage } from '@/utils/CommonMessage';
import { AppStore } from '@/stores/store';
import axios from 'axios';
import ReportInfo from '@/views/system_set/ReportInfo.vue'; //报表信息
import ReportInfoInstrumentRpt from './components/ReportInfoInstrumentRpt.vue'; //仪器报表
import ReportAttribute from '@/views/system_set/ReportAttribute.vue'; //属性设置
import LogInfo from '@/components/LogInfo.vue'; //日志
import { formatDateTime } from '@/utils/common';

import { Document, Menu as IconMenu, Location, Setting } from '@element-plus/icons-vue';

let store = AppStore();
let conHeight = ref(document.documentElement.clientHeight || document.body.clientHeight);
let defaultProps = {
  children: 'children',
  label: 'name'
};
let treeloading = ref(false);
let isShowParentName = ref(false);
let currentKey = ref(''); //树形表格默认选中
let currentTreeNode = reactive([]);
// 页面加载时更新用户列表
let loading = ref(false);
// 弹框表单状态
let showDialog = ref(false);
let isShowCode = ref(false);
let isReadOnly = ref(true);

const size = ref('');

let { proxy }: any = getCurrentInstance();
let form = reactive({
  id: null,
  searchValue: '',
  code: '',
  searchValueMoulde: '',
  name: '',
  pointsId: '',
  paperSize: '',
  moduleId: '',
  reportTemplate: '',
  saveAsName: '',
  isUse: '',
  type: '0',
  parentName: '',
  parentId: ''
});

let moduleAndPointList: any = reactive([]); //模块与功能树形结构数据
let reportList: any = reactive([]); //报表列表

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];

let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});
let moduleList: any = reactive([]); //模块下拉列表
let pointList: any = reactive([]); //功能下拉列表
let type = '0'; //业务表单类型为0

let fileList: any = reactive([]); //上传的文件列表
let keywordsMoudle = ref('');
let moduleId = '';
let pointsId = '';
let selectfilecount = 0;
let refReport: any = ref(null);
//点击当前行时；把父组件中的当前行数据传给子组件  <ReportAttribute ref="refReport"/>
function reportRowClick({ row }: any) {
  refReport.value.initPage(row);
}
function selectOpen() {
  if (moduleId === '' && pointsId === '') {
    VxeMessage('请选择相应的功能模块或功能点', 'error');
    return;
  }
}
//上传文件状态改变
function fileSelectChange(file) {
  if (moduleId === '' && pointsId === '') {
    VxeMessage('请选择相应的功能模块或功能点', 'error');
    return;
  }
  selectfilecount++;
  let name = '';
  let reportTemplate = '';
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = (e: any) => {
    reportTemplate = e.target.result
      .toString()
      .replace('data:application/octet-stream;base64,', '');
    name = file.name;
    let $el = proxy.$refs.uploadFilemany;
    $el.clearFiles();

    const data = {
      moduleId: moduleId,
      pointsId: pointsId,
      reportTemplate: reportTemplate,
      name: name,
      reportName: '业务表单',
      type: type
    };
    const url = '/api/pubReport/saveBatch';
    proxy.$http
      .post(url, data)
      .then((res) => {
        selectfilecount--;
        if (selectfilecount <= 0) {
          getReportList();
          ElMessage({
            message: '创建成功',
            type: 'success'
          });
        }
      })
      .catch((err) => {
        ElMessage({
          message: '创建异常',
          type: 'error'
        });
      });
  };
}

function uploadSuccess(response, file, fileList) {
  selectfilecount--;
  if (selectfilecount <= 0) {
    //刷新列表
  }
}

// 删除上传文件
function fileRemove(file, fileList) {
  //this.workListFileForm.filePath = '';
}

getModuleList();
getPointList();

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    handleSearch(form.searchValue);
  }
}

// 查询/刷新
function handleSearch(row: any) {
  loading.value = true;
  reportList.length = 0;
  const url = '/api/pubReport/getReportList';
  proxy.$http
    .get(url, {
      params: { pageIndex: page.currentPage, pageSize: page.pageSize, keywords: row, type: type }
    })
    .then((res: any) => {
      reportList.push(...res.data.reportList.records);

      page.totalResult = res.data.reportList.total;
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('查询刷新失败', 'error');
    });
}

//下载
function handleDownload(row) {
  // 以之前的post请求举例
  axios
    .get((window as any).apiUrl.VUE_APP_PRINT_URL + '/download-report-file/' + row.name, {
      responseType: 'blob'
    })
    .then((res: any) => {
      const fileName = row.name;
      //const blob = new Blob([JSON.stringify(data)], ...)
      const blob = new Blob([res.data], {});
      let dom = document.createElement('a');
      let url = window.URL.createObjectURL(blob);
      dom.href = url;
      dom.download = decodeURI(fileName);
      dom.style.display = 'none';
      document.body.appendChild(dom);
      dom.click();
      dom.parentNode.removeChild(dom);
      window.URL.revokeObjectURL(url);
    })
    .catch((err) => {
      console.log('异常', err);
    });
}

//报告编辑
function gotoEditPage(row) {
  if (row) {
    window.open((window as any).apiUrl.VUE_APP_PRINT_URL + '/designer/edit/' + row.name, '_blank');
    return;
  }
  window.open((window as any).apiUrl.VUE_APP_PRINT_URL + '/designer', '_blank');
}

//   watch(reportList, (newData) => {
//   const usedRows = newData.filter(item => item.isUse === "0");
//   if (usedRows.length > 1) {
//     usedRows.forEach(row => {
//       if (row.isUse === "0") {

//         row.isUse = "1";

//       }
//     });
//   }
// }, { deep: true });

//更改开关状态
function handleSwitchChange(row) {
  // console.log('row',row);

  reportList.forEach((item) => {
    if (item !== row) {
      item.isUse = '1';
    }
  });
  const data = {
    id: row.id,
    name: row.name,
    isUse: row.isUse,
    pointsId: row.pointsId,
    type: type
  };
  const url = 'api/pubReport/updateUse';
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      if (res.status.code === 200) {
        // getReportList();

        ElMessage({
          message: res.status.msg,
          type: 'success'
        });
      } else {
        VxeMessage(res.status.msg, 'error');
      }
    })
    .catch((err: any) => {
      VxeMessage('失败', 'error');
    });
}
//获取所有模块
function getModuleList() {
  moduleList.length = 0;
  proxy.$http.post('/api/pubReport/getModuleDictList').then((res) => {
    moduleList.push(...res.data);
    //console.log('moduleList数据列表', res.data);
  });
}
//获取所有功能点
function getPointList() {
  pointList.length = 0;
  proxy.$http.post('/api/pubReport/getFormDictList').then((res) => {
    // console.log('数据列表getPointList', res.data);
    pointList.push(...res.data);
  });
}
const filteredPointList = ref([]);

function onModuleChange() {
  const selectedModuleId = form.moduleId;
  filteredPointList.value = pointList.filter((point) => point.moduleId === selectedModuleId);
  form.pointsId = filteredPointList.value.length > 0 ? filteredPointList.value[0].id : '';
}

function handleClickType(node) {
  // proxy.$refs.dataTreeRef.setCurrentNode(node);
  // console.log('node', node);
  pointsId = '';
  moduleId = '';
  if (node.children === null) {
    //表示根据功能点查询
    pointsId = node.commonId;
  } else {
    //根据功能模块+功能点联查
    moduleId = node.moduleId;
  }
  getReportList();
}

function deleteReport(row) {
  const data = {
    id: row.id,
    name: row.name
  };
  const url = 'api/pubReport/deleteReport';
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      if (res.status.code === 200) {
        getReportList();
        ElMessage({
          message: res.status.msg,
          type: 'success'
        });
      } else {
        VxeMessage(res.status.msg, 'error');
      }
    })
    .catch((err: any) => {
      VxeMessage('失败', 'error');
    });
}

function getRowClassName({ row }) {
  if (row.parentId !== null && row.parentId !== '' && row.parentId !== undefined) {
    return 'row-green';
  }
  return null;
}

function isShowbutton(row) {
  let userInfo = store.userInfo;

  if (userInfo.realname === '管理员') {
    return true;
  }

  if (row.parentId !== null && row.parentId !== '' && row.parentId !== undefined) {
    return true;
  }
}

//点击每页数量
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  getReportList();
}

// 用户输入关键字
// getReportList();
getModuleAndDictFormList();

// 获取报表信息
function getReportList() {
  loading.value = true;
  reportList.length = 0; //放入数据前清空数
  const data = {
    params: {
      pageIndex: page.currentPage,
      pageSize: page.pageSize,
      moduleId: moduleId,
      pointsId: pointsId,
      type: type
    }
  };
  const url = 'api/pubReport/getReportList';
  proxy.$http
    .get(url, data)
    .then((res: any) => {
      res.data.reportList.records.forEach((item) => {
        return (item.editTime = formatDateTime(item.editTime, 'yyyy-MM-dd hh:mm:ss'));
      });
      reportList.push(...res.data.reportList.records);
      page.totalResult = res.data.reportList.total;
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('搜索报表列表失败', 'error');
    });
}

//moduleAndPointList 获取业务表单中的树形菜单----模块---功能

function getModuleAndDictFormList() {
  treeloading.value = true;
  moduleAndPointList.length = 0; //放入数据前清空数

  const url = 'api/pubReport/getModuleAndDictFormList';
  proxy.$http
    .post(url)
    .then((res: any) => {
      moduleAndPointList.push(...res.data);
      currentKey.value = moduleAndPointList[0].children[0].commonId;
      currentTreeNode = moduleAndPointList[0].children[0];
      proxy.$nextTick(() => {
        proxy.$refs.dataTreeRef.setCurrentKey(currentKey.value);
        handleClickType(currentTreeNode);
      });
      treeloading.value = false;
    })
    .catch((err: any) => {
      treeloading.value = false;
      VxeMessage('获取模块与功能树状结构失败', 'error');
    });
}

let title = ref('');
let isUpload = ref(true);
let addType = ref('');

function handleEide(row, type) {
  //let rowName = row.name;
  addType.value = type;
  if (type === 1) {
    //另存为模版
    title.value = '另存为模版';
    form.name = '';
    //隐藏上传按钮
    isUpload.value = false;
    isShowParentName.value = true;
    isShowCode.value = false;
    if (row.parentName === null || row.parentName === '' || row.parentName === undefined) {
      form.parentName = row.name;
    } else {
      form.parentName = row.parentName;
    }
    isReadOnly.value = true;
    const url = '/api/pub/getReportAsName';
    proxy.$http
      .post(url)
      .then((res) => {
        form.name = '(自定义)' + res.data;
      })
      .catch((err) => {
        console.log(err);
        ElMessage({
          message: '获取另存为名称异常',
          type: 'error'
        });
      });
  } else if (type === 2) {
    title.value = '修改模版';
    form.name = row.name;
    isShowCode.value = true;
    if (row.parentName !== null && row.parentName !== '' && row.parentName !== undefined) {
      form.parentName = row.parentName;
      isShowParentName.value = true;
    }
    isReadOnly.value = true;
  }
  showDialog.value = true;
  form.moduleId = row.moduleId;
  form.code = row.code;
  form.paperSize = row.paperSize;
  form.pointsId = row.pointsId;
  form.reportTemplate = row.reportTemplate;
  form.saveAsName = row.name;
  form.id = row.id;
  form.parentId = row.parentId;
  filteredPointList.value = pointList.filter((point) => point.moduleId === row.moduleId);
}

const fileUploadAgain = ref();
//重新上传文件状态改变
function uploadTemplateFileAgain(file) {
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = (e: any) => {
    form.reportTemplate = e.target.result
      .toString()
      .replace('data:application/octet-stream;base64,', '');
    form.name = file.name;
    let $el = proxy.$refs.fileUploadAgain;

    $el.clearFiles();
  };
}

function clearFormAndobj() {
  (form.id = null),
    (form.searchValue = ''),
    (form.code = ''),
    (form.searchValueMoulde = ''),
    (form.name = ''),
    (form.pointsId = ''),
    (form.paperSize = ''),
    (form.moduleId = ''),
    (form.parentName = '');
  (form.type = type), (form.parentId = ''), (form.saveAsName = '');
  showDialog.value = false;
  //放开上传按钮
  isUpload.value = true;
  addType.value = '';
  isShowParentName.value = false;
  isShowCode.value = false;
}

// 弹框取消
function closeDialog() {
  let $form = proxy.$refs.reportForm;
  $form.resetFields();
  clearFormAndobj();
}

// 点击新增
function handleAdd() {
  clearFormAndobj();
  isReadOnly.value = false;
  showDialog.value = true;
  addType.value = '0'; //新增
  title.value = '新建业务表单模版';
}

// 表格规则
let formRule = ref({
  // code: [
  //   {
  //     required: true,
  //     message: '请输入编码',
  //     trigger: 'blur'
  //   },
  //   {
  //     min: 2,
  //     max: 20,
  //     message: '长度为2到32个字符',
  //     trigger: 'blur'
  //   }
  // ],
  name: [
    {
      required: true,
      message: '请输入报表名称',
      trigger: 'blur'
    }
  ],
  paperSize: [
    {
      required: true,
      message: '请选择纸张规格',
      trigger: 'blur'
    }
  ]
});

// 弹框保存
function saveHandler() {
  let $form = proxy.$refs.reportForm;
  $form.validate((valid: any) => {
    // 表单校验
    //
    if (!valid) {
      return false;
    } else {
      if (form.id == '' || form.id == null || form.id == undefined) {
        const url = '/api/pubReport/addReportBusiness';
        let PubReport = form;
        proxy.$http
          .post(url, PubReport)
          .then((res) => {
            getReportList();
            clearFormAndobj();
            $form.resetFields();

            ElMessage({
              message: '创建成功',
              type: 'success'
            });
          })
          .catch((err) => {
            console.log(err);
            ElMessage({
              message: '创建异常',
              type: 'error'
            });
          });
      } else {
        // 两种情况  addType 1 另存为  2 修改
        if (addType.value === 1) {
          const url = '/api/pubReport/saveAsReportBusiness';
          let PubReport = form;
          proxy.$http
            .post(url, PubReport)
            .then((res) => {
              clearFormAndobj();
              getReportList();
              ElMessage({
                message: '另存为成功',
                type: 'success'
              });
            })
            .catch((err) => {
              console.log(err);
              ElMessage({
                message: '另存为异常',
                type: 'error'
              });
            });
        } else if (addType.value === 2) {
          //修改模版
          const url = '/api/pubReport/updateReportBusiness';
          let PubReport = form;
          proxy.$http
            .post(url, PubReport)
            .then((res) => {
              if (res.status.code === 200) {
                clearFormAndobj();
                getReportList();
                ElMessage({
                  message: res.status.msg,
                  type: 'success'
                });
              } else {
                VxeMessage(res.status.msg, 'error');
              }
            })
            .catch((err) => {
              console.log(err);
              ElMessage({
                message: '修改异常',
                type: 'error'
              });
            });
        }
      }
    }
  });
}

// 首页模块 驾驶舱表单数据、
const indexFrom = ref({
  num: null
});
</script>

<style lang="scss" scoped>
#reportManager {
  width: 100%;
  height: 100%;

  .bodyContent {
    // 面包屑40px  上下间距10px
    height: calc(100% - 60px);
    .sampleType {
      .tools-tree {
        min-width: 168px;
        padding: 0 5px 5px 5px;
        font-size: $font-size;
        border: none;
      }
    }
    :deep(.el-tabs) {
      height: 100%;
      .el-tabs__content {
        height: calc(100% - 39px);
        padding: 0 !important;
      }

      // 附加按钮间距
      .button-blue {
        margin: 5px 0 5px 5px;
      }
    }

    .businessBox {
      height: calc(100%);
      .tablebox {
        height: calc(100% - 40px);
        .reportList {
          height: calc(100% - 32px);
          :deep(.vxe-table--render-wrapper) {
            height: 100%;
            .vxe-table--main-wrapper {
              height: 100%;
              .vxe-table--body-wrapper {
                height: calc(100% - 26px) !important;
              }
            }
          }
          :deep(.vxe-table--render-default) {
            height: calc(100% - 36px) !important;
          }
        }
      }
    }
  }

  :deep(.el-tab-pane) {
    height: 100%;
  }

  :deep(.splitpanes) {
    height: 100%;
  }
  :deep(.reportInfoList.vxe-table .vxe-body--row.row-green) {
    background-color: rgb(255, 255, 225); // color: #fff;
  }
}
</style>
